﻿using System;
using System.Net.Sockets;
using System.IO;
using System.Net;
using System.ComponentModel;
using System.Collections;


namespace ThePushCSharp
{
    public class Server
    {
        public bool active;
        public TcpListener tcpListener;
        public PlayerConnection[] playerConnections;
        public int numberOfPlayers;
        public ThePush game;

        public Server(ThePush game)
        {
            active = false;
            this.game = game;
        }

        //Starts a server on the port with a number of players available to join
        public void startServer(int port, int maxPlayers)
        {
            try
            {
                IPAddress localAddr = IPAddress.Parse("127.0.0.1");
                tcpListener = new TcpListener(localAddr, port);
                tcpListener.Start();

                numberOfPlayers = 0;
                playerConnections = new PlayerConnection[maxPlayers];

                active = true;
            }
            catch
            {
                return;
            }

        }

        //Accepts a new connection if there is room in the game
        public bool acceptNewConnection()
        {
            if (numberOfPlayers < playerConnections.Length)
            {
                Socket newSocket = tcpListener.AcceptSocket();
                playerConnections[numberOfPlayers] = new PlayerConnection(newSocket);
                numberOfPlayers++;
                return true;
            }

            return false;
        }

        //Frees up all the playerConnections ONLY if this was active
        public void close()
        {
            if (!active)
                return;

            for (int i = 0; i < numberOfPlayers; i++)
                playerConnections[i].close();
        }

        //Attempts to receive data from all of the player connections
        public void recvAll()
        {
            for (int i = 0; i < playerConnections.Length; i++)
            {
                if (recv(i) == -1)
                {
                    //Error!
                }
            }
        }

        //Helper function to receive data on a specific player connection
        private int recv(int index)
        {
            if (index >= 0 && index < playerConnections.Length)
            {
                string s = playerConnections[index].recv();
            }

            return 0;
        }

        //Attemps to send data to the player connection
        public int send(int index, char messageType, String parameters)
        {
            if (index >= 0 && index < playerConnections.Length)
            {
                return playerConnections[index].send(messageType, parameters);
            }

            return -1;
        }

    }
}